<template>
  <div>
    <page-box>
      <template #top>
        <alert-msg
          content="在平台触发某些特定事件时，可以通过配置事件推送，将相关事件的内容推送到指定的接口中，支持推送多个地址，基于这些推送的数据，可以实现更灵活的统计分析功能"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="onFetchData">查询</el-button>
        <el-button type="primary" @click="onAdd">新建</el-button>
      </template>
      <template #table>
        <resize-table
          :showPagination="true"
          :data="tableData"
          :pagingData="pagingData"
          :headers="headers"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
        >
          <!-- 事件类型 -->
          <template #eventType="{ scope }">
            <span class="xiami"> {{ getEventType(scope.row.eventType) }}</span>
          </template>

          <template #updateUser="{ scope }">
            <span class="updateUser">
              {{ userObj && userObj[scope.row.updateUser] ? userObj[scope.row.updateUser].name : '--' }}
            </span>
          </template>
          <template #oprate="{ scope }">
            <span class="oprate-span" @click="onEdit(scope.row)">编辑</span>
            <span class="oprate-span" @click="onDelete(scope.row)">删除</span>
          </template>
        </resize-table>
      </template>
    </page-box>
    <add-edit-event ref="addEditEventRef" :typeArr="typeMap" @onRefresh="onFetchData"></add-edit-event>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, onBeforeMount, getCurrentInstance, toRefs, computed, nextTick } from 'vue'
import pageBox from '@common/components/page-box.vue'
import searchForm from '@common/components/base-form/form.vue'
import resizeTable from '@common/components/resize-table/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import addEditEvent from './add-edit-event.vue'
import { commonStore } from '@/common/store/modules/common'
import { ElMessageBox, ElMessage } from 'element-plus'
export default defineComponent({
  name: 'eventPush',
  components: { searchForm, resizeTable, pageBox, alertMsg, addEditEvent },
  setup() {
    const INSTANCE: any = getCurrentInstance()
    const typeMap = [
      { label: '外呼振铃事件', value: 'dialoutRing' },
      { label: '外呼挂机事件', value: 'dialoutHangup' },
      { label: '来电振铃事件', value: 'incomingRing' },
      { label: '来电挂机事件', value: 'incomingHangup' },
      { label: '通话记录推送事件', value: 'cdr' },
      { label: '客户接通事件', value: 'link' },
      { label: '座席状态变化事件', value: 'callStatus' },
      { label: '媒体识别挂机原因事件', value: 'mediaFailreason' },
      { label: '电话条登录状态事件', value: 'loginStatus' },
      { label: '排队开始事件', value: 'QueueStart' },
      { label: '排队结束事件', value: 'QueueEnd' },
      { label: '备件变更', value: 'SALE_SPARE_CHANGE' },
      { label: '备件入库', value: 'SALE_SPARE_RK' },
      { label: '备件出库', value: 'SALE_SPARE_CK' },
      { label: '服务项目品类变更', value: 'SALE_SERVICE_PROJECT_ITEM_CHANGE' }
    ]
    const STATE = reactive({
      // 动态表单检索
      fieldList: [
        {
          name: '事件类型',
          field: 'eventType',
          type: 'dropdown',
          choices: typeMap,
          multiple: true
        }
      ],
      // 检索表单
      form: { eventType: '' },
      // 表格数据
      tableData: [],
      headers: [
        { label: '事件类型', prop: 'eventType', show: true, custom: true },
        { label: '推送地址', prop: 'pushUrl', show: true },
        { label: '说明', prop: 'description', show: true },
        { label: '最后操作人', prop: 'updateUser', show: true, custom: true },
        { label: '最后更新时间', prop: 'updateTime', show: true },
        { label: '操作', prop: 'oprate', show: true, width: 120 }
      ],
      // 分页数据
      pagingData: { page: 1, total: 0, limit: 10 },
      getEventType: (type: string) => {
        const arr = typeMap
        let str = '--'
        arr.forEach((item: any) => {
          if (item.value === type) {
            str = item.label
          }
        })
        return str
      }
    })
    // 快捷表单检索
    const searchFun = () => {
      STATE.pagingData.page = 1
      onFetchData()
    }

    // 新建事件
    const onAdd = () => {
      INSTANCE?.refs.addEditEventRef.openOrCloseDrawer()
    }

    // 编辑事件
    const onEdit = (data: any) => {
      INSTANCE?.refs.addEditEventRef.openOrCloseDrawer(data || {})
    }

    // 删除推送事件
    const onDelete = (data: any) => {
      ElMessageBox.confirm('确定删除该事件类型吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ElMessage({ message: '删除成功', type: 'success' })
          onFetchData()
        })
        .catch((e) => {
          console.log(e)
        })
    }
    // 获取所有员工的map信息
    const userObj: any = computed(() => {
      return commonStore().publicCache.userCacheObj || {}
    })

    // 获取事件推送列表
    const onFetchData = () => {
      // const sendData = {
      //   ...STATE.form,
      //   limit: STATE.pagingData.limit,
      //   page: STATE.pagingData.page
      // }
      // queryServiceTime(sendData).then((res: any) => {
      //   if (res.success && res.data) {
      //     STATE.tableData = res.data.list || []
      //     STATE.pagingData.total = res.data.count || 0
      //   }
      // })
      console.log('查列表==========')
      const res: any = {
        success: true,
        message: '200 ok!',
        code: '200',
        data: {
          count: 1,
          list: [
            {
              _id: '633141d84a8a7b63c478b5ab',
              accountId: '2001432',
              pushUrl: 'http://www.baidu.com',
              eventType: 'dialoutRing',
              description: '',
              createTime: '2022-09-26 14:08:24',
              updateTime: '2022-09-26 14:08:24',
              createUser: '579752078334488576',
              updateUser: '579752078334488576'
            },
            {
              _id: '633141d84a8a7b63c478b5ab',
              accountId: '2001432',
              pushUrl: 'http://www.baidu.com',
              eventType: 'incomingHangup',
              description: '我升级内置',
              createTime: '2022-09-26 14:08:24',
              updateTime: '2022-09-26 14:08:24',
              createUser: '580504212288270336',
              updateUser: '580504212288270336'
            }
          ]
        }
      }
      const list = res.data.list || []
      if (list.length === 0) {
        const page = Math.ceil(res.data.count / STATE.pagingData.limit)
        if (!res.data.count) {
          // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
          STATE.pagingData.page = 1
        } else {
          // 删除到最后一个回到上一页
          STATE.pagingData.page = page
          onFetchData()
          return false
        }
      }
      STATE.tableData = res.data.list || []
      STATE.pagingData.total = res.data.count || 0
    }
    const handleCurrentChange = (page: number) => {
      STATE.pagingData.page = page
      onFetchData()
    }

    const handleSizeChange = (size: number) => {
      STATE.pagingData.limit = size
      onFetchData()
    }
    // 首次获取列表
    onBeforeMount(() => {
      onFetchData()
    })
    return {
      ...toRefs(STATE),
      onEdit,
      onAdd,
      onFetchData,
      handleCurrentChange,
      handleSizeChange,
      searchFun,
      onDelete,
      userObj,
      typeMap
    }
  }
})
</script>

<style lang="stylus" scoped>
.oprate-span
  color var(--mc-main-color)
  cursor pointer
  padding-right 10px
</style>
